using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UI.BankingPanel.Data;
using System.IO.Compression;
using System.Linq;

/// <summary>
/// 简单的Excel导出器
/// 生成标准的Excel .xlsx文件格式
/// 使用Unity内置的压缩功能
/// </summary>
public static class SimpleExcelExporter
{
    /// <summary>
    /// 导出押注数据到Excel文件
    /// </summary>
    /// <param name="bankingData">银行数据</param>
    /// <param name="fileName">文件名（不含扩展名）</param>
    /// <param name="copyToClipboard">是否复制信息到粘贴板</param>
    /// <returns>导出结果信息</returns>
    public static ExportResult ExportBankingDataToExcel(BankingData bankingData, string fileName = null, bool copyToClipboard = true)
    {
        try
        {
            if (bankingData == null)
            {
                return new ExportResult(false, "数据为空，无法导出");
            }

            // 生成文件名
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = $"押注数据_{DateTime.Now:yyyyMMdd_HHmmss}";
            }

            // 获取导出路径
            string filePath = GetExportPath(fileName + ".xlsx");
            
            // 生成Excel文件
            CreateExcelFile(bankingData, filePath);
            
            // 复制信息到粘贴板
            if (copyToClipboard)
            {
                string clipboardContent = GenerateClipboardContent(bankingData, filePath);
                CopyToClipboard(clipboardContent);
            }
            
            Debug.Log($"[SimpleExcelExporter] Excel文件导出成功: {filePath}");
            
            string resultMessage = $"Excel导出成功！\n文件路径: {filePath}";
            if (copyToClipboard)
            {
                resultMessage += "\n数据摘要已复制到粘贴板";
            }
            
            return new ExportResult(true, resultMessage, filePath);
        }
        catch (Exception ex)
        {
            Debug.LogError($"[SimpleExcelExporter] Excel导出失败: {ex.Message}\n{ex.StackTrace}");
            return new ExportResult(false, $"Excel导出失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 创建Excel文件
    /// </summary>
    /// <param name="bankingData">银行数据</param>
    /// <param name="filePath">文件路径</param>
    private static void CreateExcelFile(BankingData bankingData, string filePath)
    {
        // 确保目录存在
        string directory = Path.GetDirectoryName(filePath);
        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }

        // 使用FileStream和ZipArchive创建xlsx文件
        using (var fileStream = new FileStream(filePath, FileMode.Create))
        using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create))
        {
            // 创建Excel文件结构
            CreateExcelStructure(archive, bankingData);
        }
    }

    /// <summary>
    /// 创建Excel文件结构
    /// </summary>
    /// <param name="archive">ZIP归档</param>
    /// <param name="bankingData">银行数据</param>
    private static void CreateExcelStructure(ZipArchive archive, BankingData bankingData)
    {
        // 创建各种XML文件
        CreateContentTypes(archive);
        CreateRels(archive);
        CreateApp(archive);
        CreateCore(archive);
        CreateWorkbook(archive);
        CreateWorkbookRels(archive);
        CreateWorksheet(archive, bankingData);
        CreateSharedStrings(archive);
        CreateStyles(archive);
    }

    /// <summary>
    /// 创建[Content_Types].xml
    /// </summary>
    private static void CreateContentTypes(ZipArchive archive)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<Types xmlns=""http://schemas.openxmlformats.org/package/2006/content-types"">
    <Default Extension=""rels"" ContentType=""application/vnd.openxmlformats-package.relationships+xml""/>
    <Default Extension=""xml"" ContentType=""application/xml""/>
    <Override PartName=""/xl/workbook.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml""/>
    <Override PartName=""/xl/worksheets/sheet1.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml""/>
    <Override PartName=""/xl/sharedStrings.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml""/>
    <Override PartName=""/xl/styles.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml""/>
    <Override PartName=""/docProps/core.xml"" ContentType=""application/vnd.openxmlformats-package.core-properties+xml""/>
    <Override PartName=""/docProps/app.xml"" ContentType=""application/vnd.openxmlformats-officedocument.extended-properties+xml""/>
</Types>";
        
        WriteToArchive(archive, "[Content_Types].xml", content);
    }

    /// <summary>
    /// 创建_rels/.rels
    /// </summary>
    private static void CreateRels(ZipArchive archive)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships"">
    <Relationship Id=""rId1"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"" Target=""xl/workbook.xml""/>
    <Relationship Id=""rId2"" Type=""http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"" Target=""docProps/core.xml""/>
    <Relationship Id=""rId3"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"" Target=""docProps/app.xml""/>
</Relationships>";
        
        WriteToArchive(archive, "_rels/.rels", content);
    }

    /// <summary>
    /// 创建docProps/app.xml
    /// </summary>
    private static void CreateApp(ZipArchive archive)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<Properties xmlns=""http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"" xmlns:vt=""http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"">
    <Application>Unity坐庄收款系统</Application>
    <DocSecurity>0</DocSecurity>
    <ScaleCrop>false</ScaleCrop>
    <SharedDoc>false</SharedDoc>
    <HyperlinksChanged>false</HyperlinksChanged>
    <AppVersion>1.0</AppVersion>
</Properties>";
        
        WriteToArchive(archive, "docProps/app.xml", content);
    }

    /// <summary>
    /// 创建docProps/core.xml
    /// </summary>
    private static void CreateCore(ZipArchive archive)
    {
        string now = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ");
        string content = $@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<cp:coreProperties xmlns:cp=""http://schemas.openxmlformats.org/package/2006/metadata/core-properties"" xmlns:dc=""http://purl.org/dc/elements/1.1/"" xmlns:dcterms=""http://purl.org/dc/terms/"" xmlns:dcmitype=""http://purl.org/dc/dcmitype/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
    <dc:title>押注数据报表</dc:title>
    <dc:creator>Unity坐庄收款系统</dc:creator>
    <dcterms:created xsi:type=""dcterms:W3CDTF"">{now}</dcterms:created>
    <dcterms:modified xsi:type=""dcterms:W3CDTF"">{now}</dcterms:modified>
</cp:coreProperties>";
        
        WriteToArchive(archive, "docProps/core.xml", content);
    }

    /// <summary>
    /// 创建xl/workbook.xml
    /// </summary>
    private static void CreateWorkbook(ZipArchive archive)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"">
    <sheets>
        <sheet name=""押注数据"" sheetId=""1"" r:id=""rId1""/>
    </sheets>
</workbook>";
        
        WriteToArchive(archive, "xl/workbook.xml", content);
    }

    /// <summary>
    /// 创建xl/_rels/workbook.xml.rels
    /// </summary>
    private static void CreateWorkbookRels(ZipArchive archive)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships"">
    <Relationship Id=""rId1"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"" Target=""worksheets/sheet1.xml""/>
    <Relationship Id=""rId2"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"" Target=""sharedStrings.xml""/>
    <Relationship Id=""rId3"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"" Target=""styles.xml""/>
</Relationships>";
        
        WriteToArchive(archive, "xl/_rels/workbook.xml.rels", content);
    }

    /// <summary>
    /// 创建工作表数据
    /// </summary>
    private static void CreateWorksheet(ZipArchive archive, BankingData bankingData)
    {
        var sb = new StringBuilder();
        sb.AppendLine(@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>");
        sb.AppendLine(@"<worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"">");
        sb.AppendLine(@"<sheetData>");

        int rowIndex = 1;
        
        // 标题行
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine(@"<c r=""A1"" t=""inlineStr""><is><t>押注数据导出报表</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        // 导出时间
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>导出时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        // 赔率
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>赔率: {bankingData.odds}</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex += 2;

        // 数据汇总
        var stats = bankingData.GetStatisticsData();
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>=== 数据汇总 ===</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>项目</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}"" t=""inlineStr""><is><t>金额</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>总数据</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}""><v>{stats.revenueTotal}</v></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>自己吃码</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}""><v>{stats.eatCodeTotal}</v></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>上报数据</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}""><v>{stats.reportTotal}</v></c>");
        sb.AppendLine(@"</row>");
        rowIndex += 2;

        // 分类统计 - 总数据
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>=== 总数据 ===</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>号码</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}"" t=""inlineStr""><is><t>押注金额</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        var totalDataNumbers = GetNumbersWithDataGrouped(bankingData.GetAllNumberBetData(), DataType.Total);
        foreach (var group in totalDataNumbers)
        {
            // 显示金额和对应的号码
            string numbersText = string.Join(",", group.Value.Select(n => n.ToString("D2")));
            sb.AppendLine($@"<row r=""{rowIndex}"">");
            sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>{numbersText}</t></is></c>");
            sb.AppendLine($@"<c r=""B{rowIndex}""><v>{group.Key}</v></c>");
            sb.AppendLine(@"</row>");
            rowIndex++;
        }
        rowIndex++;

        // 分类统计 - 自己吃码
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>=== 自己吃码 ===</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>号码</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}"" t=""inlineStr""><is><t>吃码金额</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        var eatCodeNumbers = GetNumbersWithDataGrouped(bankingData.GetAllNumberBetData(), DataType.EatCode);
        foreach (var group in eatCodeNumbers)
        {
            // 显示金额和对应的号码
            string numbersText = string.Join(",", group.Value.Select(n => n.ToString("D2")));
            sb.AppendLine($@"<row r=""{rowIndex}"">");
            sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>{numbersText}</t></is></c>");
            sb.AppendLine($@"<c r=""B{rowIndex}""><v>{group.Key}</v></c>");
            sb.AppendLine(@"</row>");
            rowIndex++;
        }
        rowIndex++;

        // 分类统计 - 上报数据
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>=== 上报数据 ===</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>号码</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}"" t=""inlineStr""><is><t>上报金额</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        var reportNumbers = GetNumbersWithDataGrouped(bankingData.GetAllNumberBetData(), DataType.Report);
        foreach (var group in reportNumbers)
        {
            // 显示金额和对应的号码
            string numbersText = string.Join(",", group.Value.Select(n => n.ToString("D2")));
            sb.AppendLine($@"<row r=""{rowIndex}"">");
            sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>{numbersText}</t></is></c>");
            sb.AppendLine($@"<c r=""B{rowIndex}""><v>{group.Key}</v></c>");
            sb.AppendLine(@"</row>");
            rowIndex++;
        }

        sb.AppendLine(@"</sheetData>");
        sb.AppendLine(@"</worksheet>");

        WriteToArchive(archive, "xl/worksheets/sheet1.xml", sb.ToString());
    }

    /// <summary>
    /// 创建共享字符串
    /// </summary>
    private static void CreateSharedStrings(ZipArchive archive)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<sst xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" count=""0"" uniqueCount=""0"">
</sst>";
        
        WriteToArchive(archive, "xl/sharedStrings.xml", content);
    }

    /// <summary>
    /// 创建样式
    /// </summary>
    private static void CreateStyles(ZipArchive archive)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<styleSheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"">
    <numFmts count=""0""/>
    <fonts count=""1"">
        <font>
            <sz val=""11""/>
            <name val=""Calibri""/>
        </font>
    </fonts>
    <fills count=""2"">
        <fill>
            <patternFill patternType=""none""/>
        </fill>
        <fill>
            <patternFill patternType=""gray125""/>
        </fill>
    </fills>
    <borders count=""1"">
        <border>
            <left/>
            <right/>
            <top/>
            <bottom/>
            <diagonal/>
        </border>
    </borders>
    <cellStyleXfs count=""1"">
        <xf numFmtId=""0"" fontId=""0"" fillId=""0"" borderId=""0""/>
    </cellStyleXfs>
    <cellXfs count=""1"">
        <xf numFmtId=""0"" fontId=""0"" fillId=""0"" borderId=""0"" xfId=""0""/>
    </cellXfs>
</styleSheet>";
        
        WriteToArchive(archive, "xl/styles.xml", content);
    }

    /// <summary>
    /// 写入内容到ZIP归档
    /// </summary>
    private static void WriteToArchive(ZipArchive archive, string entryName, string content)
    {
        var entry = archive.CreateEntry(entryName);
        using (var stream = entry.Open())
        using (var writer = new StreamWriter(stream, Encoding.UTF8))
        {
            writer.Write(content);
        }
    }

    /// <summary>
    /// 获取有数据的号码列表
    /// </summary>
    private static Dictionary<int, float> GetNumbersWithData(List<NumberBetData> allData, DataType dataType)
    {
        var result = new Dictionary<int, float>();
        
        foreach (var betData in allData)
        {
            float value = 0;
            switch (dataType)
            {
                case DataType.Total:
                    value = betData.totalBetAmount;
                    break;
                case DataType.EatCode:
                    value = betData.selfBetAmount;
                    break;
                case DataType.Report:
                    value = betData.reportAmount;
                    break;
            }
            
            if (value > 0)
            {
                result[betData.number] = value;
            }
        }
        
        return result;
    }

    /// <summary>
    /// 获取按金额分组的号码列表（相同金额的号码放在一起）
    /// </summary>
    private static Dictionary<float, List<int>> GetNumbersWithDataGrouped(List<NumberBetData> allData, DataType dataType)
    {
        var result = new Dictionary<float, List<int>>();
        
        foreach (var betData in allData)
        {
            float value = 0;
            switch (dataType)
            {
                case DataType.Total:
                    value = betData.totalBetAmount;
                    break;
                case DataType.EatCode:
                    value = betData.selfBetAmount;
                    break;
                case DataType.Report:
                    value = betData.reportAmount;
                    break;
            }
            
            if (value > 0)
            {
                if (!result.ContainsKey(value))
                {
                    result[value] = new List<int>();
                }
                result[value].Add(betData.number);
            }
        }
        
        // 对每个金额组内的号码进行排序
        foreach (var group in result.Values)
        {
            group.Sort();
        }
        
        // 按金额从大到小排序
        return result.OrderByDescending(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
    }

    /// <summary>
    /// 获取导出文件路径
    /// </summary>
    private static string GetExportPath(string fileName)
    {
        string exportDir;
        
        #if UNITY_ANDROID && !UNITY_EDITOR
            exportDir = Path.Combine(Application.persistentDataPath, "Exports");
        #else
            exportDir = Path.Combine(Application.persistentDataPath, "Exports");
        #endif
        
        if (!Directory.Exists(exportDir))
        {
            Directory.CreateDirectory(exportDir);
        }
        
        return Path.Combine(exportDir, fileName);
    }

    /// <summary>
    /// 生成粘贴板内容
    /// </summary>
    /// <param name="bankingData">银行数据</param>
    /// <param name="filePath">文件路径</param>
    /// <returns>粘贴板内容</returns>
    private static string GenerateClipboardContent(BankingData bankingData, string filePath)
    {
        var sb = new StringBuilder();
        
        // 标题和时间
        sb.AppendLine("=== 押注数据导出摘要 ===");
        sb.AppendLine($"导出时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
        sb.AppendLine($"文件路径: {Path.GetFileName(filePath)}");
        sb.AppendLine($"赔率: {bankingData.odds}");
        sb.AppendLine();
        
        // 获取所有有数据的号码
        var allData = bankingData.GetAllNumberBetData();
        var numbersWithData = allData.Where(x => x.totalBetAmount > 0 || x.selfBetAmount > 0).ToList();
        
        if (numbersWithData.Count == 0)
        {
            sb.AppendLine("暂无押注数据");
            return sb.ToString();
        }
        
        // 计算汇总数据
        float totalBetSum = numbersWithData.Sum(x => x.totalBetAmount);
        float eatCodeSum = numbersWithData.Sum(x => x.selfBetAmount);
        float reportSum = numbersWithData.Sum(x => x.reportAmount);
        
        sb.AppendLine("=== 数据汇总 ===");
        sb.AppendLine($"总押注: {totalBetSum}");
        sb.AppendLine($"吃码总数: {eatCodeSum}");
        sb.AppendLine($"上报总数: {reportSum}");
        sb.AppendLine();
        
        // 分组显示数据（按金额分组）
        sb.AppendLine("=== 总数据 ===");
        var totalGroups = GetNumbersWithDataGrouped(allData, DataType.Total);
        AppendGroupedData(sb, totalGroups);
        
        sb.AppendLine("=== 自己吃码 ===");
        var eatCodeGroups = GetNumbersWithDataGrouped(allData, DataType.EatCode);
        AppendGroupedData(sb, eatCodeGroups);
        
        sb.AppendLine("=== 上报数据 ===");
        var reportGroups = GetNumbersWithDataGrouped(allData, DataType.Report);
        AppendGroupedData(sb, reportGroups);
        
        // 风险提醒
        var highRiskNumbers = numbersWithData.Where(x => x.riskValue < -1000).OrderBy(x => x.riskValue).ToList();
        if (highRiskNumbers.Count > 0)
        {
            sb.AppendLine("=== ⚠️ 高风险号码 ===");
            foreach (var number in highRiskNumbers.Take(5)) // 只显示前5个最高风险的
            {
                sb.AppendLine($"{number.number:D2}: 风险值 {number.riskValue:F0}");
            }
            if (highRiskNumbers.Count > 5)
            {
                sb.AppendLine($"... 还有 {highRiskNumbers.Count - 5} 个高风险号码");
            }
        }
        
        return sb.ToString();
    }
    
    /// <summary>
    /// 添加分组数据到StringBuilder
    /// </summary>
    /// <param name="sb">StringBuilder</param>
    /// <param name="groups">分组数据</param>
    private static void AppendGroupedData(StringBuilder sb, Dictionary<float, List<int>> groups)
    {
        if (groups.Count == 0)
        {
            sb.AppendLine("无数据");
            sb.AppendLine();
            return;
        }
        
        // 按金额从大到小排序
        var sortedGroups = groups.OrderByDescending(x => x.Key);
        
        foreach (var group in sortedGroups)
        {
            if (group.Key > 0) // 只显示有数据的
            {
                // 将号码列表转换为字符串，用逗号分隔
                var numbersStr = string.Join(",", group.Value.Select(n => n.ToString("D2")));
                sb.AppendLine($"{numbersStr} → {group.Key}");
            }
        }
        sb.AppendLine();
    }
    
    /// <summary>
    /// 复制内容到系统粘贴板
    /// </summary>
    /// <param name="content">要复制的内容</param>
    private static void CopyToClipboard(string content)
    {
        try
        {
            // 使用Unity的GUIUtility复制到系统粘贴板
            GUIUtility.systemCopyBuffer = content;
            Debug.Log("[SimpleExcelExporter] 数据摘要已复制到粘贴板");
        }
        catch (Exception ex)
        {
            Debug.LogWarning($"[SimpleExcelExporter] 复制到粘贴板失败: {ex.Message}");
        }
    }
    
    /// <summary>
    /// 数据类型枚举
    /// </summary>
    private enum DataType
    {
        Total,      // 总数据
        EatCode,    // 吃码
        Report      // 上报
    }
} 